"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.chatRoomRouter = void 0;
const express_1 = __importDefault(require("express"));
const log4js_1 = require("log4js");
const ClassroomEntity_1 = require("../entity/ClassroomEntity");
const ChatRoomEntity_1 = require("../entity/ChatRoomEntity");
const utils_1 = require("../../utils/utils");
const enums_1 = require("../../utils/enums");
const uuid_1 = require("uuid");
const ChatEntity_1 = require("../entity/ChatEntity");
const logger = (0, log4js_1.getLogger)('route/chatroom');
function chatRoomRouter(app) {
    const router = express_1.default.Router();
    router.post('/create', async ({ body }, res) => {
        var _a, _b;
        const { userId, username } = ((_b = (_a = app.locals.socket) === null || _a === void 0 ? void 0 : _a.handshake) === null || _b === void 0 ? void 0 : _b.query) || {};
        logger.debug('Create room: ' + JSON.stringify(body, null, 2));
        const { classId, classname, creator, members, description } = body;
        const chatMode = enums_1.ChatModeEnums.CHAT;
        const { intercom } = app.locals;
        let dbClassroom;
        try {
            if (classId) {
                dbClassroom = await ClassroomEntity_1.ClassroomEntity.findOne({ where: { classId, chatMode } });
                if (dbClassroom) {
                    for (const member of members) {
                        const hasMember = await ChatRoomEntity_1.ChatRoomEntity.findOne({ where: { classroom: dbClassroom, userId: member.userId } });
                        if (hasMember)
                            continue;
                        const chatClassroom = new ChatRoomEntity_1.ChatRoomEntity();
                        chatClassroom.id = (0, uuid_1.v4)();
                        chatClassroom.classroom = dbClassroom;
                        chatClassroom.userId = member.userId;
                        chatClassroom.joinTime = Date.now().toString();
                        await chatClassroom.save();
                        if (intercom && intercom[member.userId]) {
                            const member_socket = intercom[member.userId];
                            if (member_socket) {
                                member_socket.join(dbClassroom.classId);
                            }
                        }
                    }
                    logger.debug('Create room: 房间已存在，更新用户' + (0, utils_1.stringify)(body));
                    res.status(200).send({ result: 'OK', data: dbClassroom });
                    return;
                }
            }
            if (!dbClassroom) {
                dbClassroom = Object.assign(new ClassroomEntity_1.ClassroomEntity(), {
                    id: (0, uuid_1.v4)(),
                    classId: classId || (0, uuid_1.v4)(),
                    classname: classname,
                    creator: creator || userId,
                    classType: enums_1.RoomTypeEnums.TEMPORARY,
                    conferenceMode: enums_1.ConferenceModeEnums.DEFAULT,
                    inviteMode: enums_1.InviteModeEnums.NEED_VERIFY,
                    joinMode: enums_1.JoinModeEnums.NEED_VERIFY,
                    description: description,
                    chatMode: chatMode,
                });
                logger.debug('classroom/create: => ', dbClassroom);
                dbClassroom.createTime = Date.now().toString();
                dbClassroom.lastActiveTime = Date.now().toString();
                dbClassroom = await dbClassroom.save();
                if (chatMode === enums_1.ChatModeEnums.CHAT) {
                    for (const member of members) {
                        const chatClassroom = new ChatRoomEntity_1.ChatRoomEntity();
                        chatClassroom.id = (0, uuid_1.v4)();
                        chatClassroom.classroom = dbClassroom;
                        chatClassroom.userId = member.userId;
                        chatClassroom.joinTime = Date.now().toString();
                        await chatClassroom.save();
                        if (intercom && intercom[member.userId]) {
                            const member_socket = intercom[member.userId];
                            if (member_socket) {
                                member_socket.join(dbClassroom.classId);
                            }
                        }
                    }
                }
            }
            res.status(200).send({ result: 'OK', data: dbClassroom });
        }
        catch (error) {
            console.error(error);
            res.status(200).send({ result: 'Error', message: error });
        }
    });
    router.get('/list', async ({ query }, res) => {
        const { redisClient } = app.locals;
        const { userId } = query;
        logger.debug('list: => ', userId);
        if (userId) {
            const data = await ChatRoomEntity_1.ChatRoomEntity.createQueryBuilder('member_chatRooms')
                .leftJoinAndSelect("member_chatRooms.classroom", "classroom")
                .where("member_chatRooms.userId=:userId", { userId })
                .getMany();
            logger.debug('classroom/list: => ', data);
            for (const chatter of data) {
                const { id: roomId, classId } = chatter.classroom;
                logger.debug('classroom/chatter: => send', chatter);
                if (roomId) {
                    chatter.chat = await redisClient.hGet('chat-message', classId);
                }
            }
            logger.debug('classroom/list: => send');
            res.status(200).send({ result: 'OK', data });
        }
    });
    router.get('/list-chats', async ({ query }, res) => {
        const { userId } = query;
        console.log('personnel/list: => ');
        if (userId) {
            if (userId === 'administrator') {
                let data = await ClassroomEntity_1.ClassroomEntity.findBy({ chatMode: enums_1.ChatModeEnums.CHAT });
                data = await Promise.all(data.map(async (classroom) => {
                    return {
                        ...classroom,
                        members: await ChatRoomEntity_1.ChatRoomEntity.findBy({ classroom })
                    };
                }));
                console.log('roomMembers', data);
                res.status(200).send({ result: 'OK', data });
            }
            else {
                const data = await ChatRoomEntity_1.ChatRoomEntity.createQueryBuilder('member_chatRooms')
                    .leftJoinAndSelect("member_chatRooms.classroom", "classroom")
                    .where("member_chatRooms.userId=:userId", { userId })
                    .getMany();
                console.log('classroom/list: => ', data);
                for (const personnel of data) {
                    const { id: roomId } = personnel.classroom;
                    if (roomId) {
                        personnel.chat = await ChatEntity_1.ChatEntity.findOneBy({ roomId });
                    }
                }
                logger.debug('classroom/list: => send');
                res.status(200).send({ result: 'OK', data });
            }
        }
    });
    return router;
}
exports.chatRoomRouter = chatRoomRouter;
